package vn.com.vega.chacha.v2;

import java.util.ArrayList;
import java.util.HashMap;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.SearchScreen.SimpleContextAdapter;
import vn.com.vega.chacha.v2.Asynctask.AutoLogin;
import vn.com.vega.chacha.v2.Asynctask.AutoLogin.LoginListener;
import vn.com.vega.chacha.v2.receiver.NetworkStatusReceiver;
import vn.com.vega.music.clientserver.JsonBase;
import vn.com.vega.music.clientserver.ServerSessionInvalidListener;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.downloadmanager.DownloadUtil;
import vn.com.vega.music.player.ChaChaProgressDialog;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.custom.ChaChaDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;

public class ActivityBase extends FragmentActivity {
	public static final String LOGOUT = "app logouted";

	// Const for Google Analytic
	public interface Category {
		String selectItem = "Select Item";
		String submit = "Submit";
	}

	public interface Action {
		String selectSongPlay = "Select song";
		String playAll = "Play all song";
		String playsong = "Play song";
		String playVideo = "Play video";
		String shareOneSong = "Share song";
		String likeSong = "Like song";
		String downloadSong = "Download song";
		String searchSong = "Search song";
		String searchVideo = "Search video";
		String searchAlbum = "Search Album";
		String searchPlaylist = "SearcgPlaylist";
		String searchArtist = "Search Artist";
	}

	public boolean isDestroy = false;
	public Toast toast;
	public HashMap<String, ChaChaDialog> listFillterDialog = new HashMap<String, ChaChaDialog>();
	protected Tracker tracker;

	protected AutoLogin autoLogin;
	protected LoginListener autoLoginListener = new LoginListener() {

		@Override
		public void startLogin() {
			// TODO Auto-generated method stub
			showProgress("Đang thực hiện đăng nhập...");
		}

		@Override
		public void loginSuccess() {
			// TODO Auto-generated method stub
			hideProgress();
			showToast("Đăng nhập thành công!");
		}

		@Override
		public void loginFail(String failMessage) {
			// TODO Auto-generated method stub
			hideProgress();
			showToast("Đăng nhập thất bại!");
			actionDoWhenLogoutSuccess();
		}
	};

	protected void actionDoWhenLogoutSuccess() {
		DataStore dataStore = DataStore.getInstance();
		JsonBase.clearServerSessionInvalidListener();
		DownloadUtil.stopDownload();
		// // Stop sync thread
		// SyncUtil.stopSync(setting.getApplicationContext());
		// // Stop MusicPlayer
		Util.stop();

		// request login again
		Bundle b = new Bundle();
		b.putBoolean(LoginActivity.NEED_AUTHENTICATION, true);
		b.putString(Const.KEY_MSISDN, dataStore.getMsisdn());
		b.putString(Const.KEY_PASSWORD, dataStore.getSavedPassword());

		// setting.dataStore.setConfig(KEY_IS_LOGOUT, "true");

		b.putBoolean(LoginActivity.NEED_AUTHENTICATION, true);
		Intent login = new Intent(this, LoginActivity.class);
		login.putExtras(b);
		login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(login);
		sendStickyBroadcastLogout();
		finish();
	}

	private void doLoginAgain() {
		if (autoLogin != null) {
			autoLogin.cancel(true);
		}
		autoLogin = new AutoLogin(this, autoLoginListener);
		autoLogin.execute();
	}

	private ServerSessionInvalidListener serverSessionInvalidListener = new ServerSessionInvalidListener() {

		@Override
		public void onValidateAgain() {
			// TODO Auto-generated method stub
			doLoginAgain();
		}

		@Override
		public void onPowerExpire(String preferred_package_code, String msg) {
			// TODO Auto-generated method stub
			doLoginAgain();
		}

		@Override
		public void onLoginAgain() {
			// TODO Auto-generated method stub
			doLoginAgain();
		}
	};

	ChaChaProgressDialog progressDialog;

	public void showProgress(String message) {
		if (progressDialog == null) {
			progressDialog = new ChaChaProgressDialog(this);
		}
		progressDialog.setMessage(message);
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	public void hideProgress() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	public void showFilltter(ArrayList<String> listFillter,
			AdapterView.OnItemClickListener onItemClickListener,
			String fillterDialogName) {
		ChaChaDialog fillterDialog = listFillterDialog.get(fillterDialogName);
		if (fillterDialog != null) {
			fillterDialog.show();
			return;
		}

		// Create dialog
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ListView listType = (ListView) inflater.inflate(
				R.layout.view_fillter_poup, null);
		SimpleContextAdapter adapter = new SimpleContextAdapter(this,
				listFillter);
		listType.setAdapter(adapter);
		listType.setOnItemClickListener(onItemClickListener);
		fillterDialog = new ChaChaDialog(this, null);
		fillterDialog.setContentView(listType);
		fillterDialog.hideHeader();
		fillterDialog.hideBottomView();
		fillterDialog.setCancelable(true);
		fillterDialog.show();

		// Add to cache
		listFillterDialog.put(fillterDialogName, fillterDialog);
	}

	public void hideDialogFillter(String dialogFillterName) {
		ChaChaDialog dialog = listFillterDialog.get(dialogFillterName);
		if (dialog != null) {
			dialog.dismiss();
		}
	}

	public void showToast(String msg) {
		if (toast == null) {
			toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		}
		toast.setText(msg);
		toast.show();
	}

	public void showWarningNotConnectInternet() {
		showToast("Không có kết nối internet");
	}

	public boolean checkIsConnect() {
		if (!NetworkStatusReceiver.isConnected()) {
			showWarningNotConnectInternet();
		}
		return NetworkStatusReceiver.isConnected();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unListenerLogout();
		isDestroy = true;

		View root = ((ViewGroup) getWindow().getDecorView()
				.findViewById(android.R.id.content).getRootView())
				.getChildAt(0);

		unbindDrawables(root);
		System.gc();
	}

	private BroadcastReceiver logoutReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			appLogouted();
		}
	};

	protected void appLogouted() {
		finish();
	}

	protected void logoutListener() {
		IntentFilter intentFilter = new IntentFilter(LOGOUT);
		registerReceiver(logoutReceiver, intentFilter);
	}

	protected void unListenerLogout() {
		try {
			unregisterReceiver(logoutReceiver);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	protected void removeLogoutStickyBroadCast() {
		Intent intent = new Intent(LOGOUT);
		removeStickyBroadcast(intent);
	}

	protected void sendStickyBroadcastLogout() {
		Intent intent = new Intent(LOGOUT);
		sendStickyBroadcast(intent);
	}

	private void unbindDrawables(View view) {
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if (view instanceof ViewGroup) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				unbindDrawables(((ViewGroup) view).getChildAt(i));
			}
			try {
				if (view instanceof AdapterView) {
					((AdapterView) view).setAdapter(null);
				} else {
					((ViewGroup) view).removeAllViews();
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		logoutListener();
		// if (Build.VERSION.SDK_INT >= 9) {
		// StrictMode.ThreadPolicy policy = new
		// StrictMode.ThreadPolicy.Builder()
		// .permitAll().build();
		// StrictMode.setThreadPolicy(policy);
		// }
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	// Google Analytic util
	public void trackEvent(String eventCategory, String eventAction,
			String eventLabel, long eventValue) {
		if (tracker == null) {
			EasyTracker.getInstance().setContext(this);
			tracker = EasyTracker.getTracker();
		}
		tracker.trackEvent(eventCategory, eventAction, eventLabel, eventValue);
	}

	public void trackPageView(String name) {
		if (tracker == null) {
			EasyTracker.getInstance().setContext(this);
			tracker = EasyTracker.getTracker();
		}
		tracker.trackView(name);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		JsonBase.clearServerSessionInvalidListener();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		JsonBase.setServerSessionInvalidListener(serverSessionInvalidListener);
	}
}
